package com.autoglm.android.core.services

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

/**
 * 应用启动服务，负责启动和管理第三方应用
 */
class AppLaunchService(private val context: Context) {
    
    companion object {
        private const val TAG = "AppLaunchService"
        private const val DEFAULT_LAUNCH_TIMEOUT = 5000L // 默认启动超时时间(毫秒)
    }
    
    /**
     * 检查应用是否已安装
     * 
     * @param packageName 应用包名
     * @return 应用是否已安装
     */
    fun isAppInstalled(packageName: String): Boolean {
        return try {
            context.packageManager.getApplicationInfo(packageName, 0)
            true
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }
    
    /**
     * 获取应用名称
     * 
     * @param packageName 应用包名
     * @return 应用名称，如果应用未安装则返回null
     */
    fun getAppName(packageName: String): String? {
        return try {
            val packageManager = context.packageManager
            val applicationInfo = packageManager.getApplicationInfo(packageName, 0)
            packageManager.getApplicationLabel(applicationInfo).toString()
        } catch (e: PackageManager.NameNotFoundException) {
            null
        }
    }
    
    /**
     * 获取应用版本信息
     * 
     * @param packageName 应用包名
     * @return 应用版本名称，如果应用未安装则返回null
     */
    fun getAppVersion(packageName: String): String? {
        return try {
            val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                context.packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
            } else {
                @Suppress("DEPRECATION")
                context.packageManager.getPackageInfo(packageName, 0)
            }
            packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            null
        }
    }
    
    /**
     * 启动应用
     * 
     * @param packageName 应用包名
     * @return 启动是否成功
     */
    suspend fun launchApp(packageName: String): Boolean = withContext(Dispatchers.Main) {
        try {
            if (!isAppInstalled(packageName)) {
                Log.e(TAG, "Application not installed: $packageName")
                return@withContext false
            }
            
            val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName)
            if (launchIntent == null) {
                Log.e(TAG, "No launch intent found for: $packageName")
                return@withContext false
            }
            
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(launchIntent)
            
            // 等待应用启动
            delay(1000)
            return@withContext true
        } catch (e: Exception) {
            Log.e(TAG, "Error launching app: $packageName", e)
            return@withContext false
        }
    }
    
    /**
     * 使用深链接启动应用到特定页面
     * 
     * @param deepLink 深链接地址
     * @return 启动是否成功
     */
    suspend fun launchWithDeepLink(deepLink: String): Boolean = withContext(Dispatchers.Main) {
        try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(deepLink))
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            
            context.startActivity(intent)
            delay(1000)
            return@withContext true
        } catch (e: Exception) {
            Log.e(TAG, "Error launching with deep link: $deepLink", e)
            return@withContext false
        }
    }
    
    /**
     * 关闭应用
     * 
     * @param packageName 应用包名
     * @return 操作是否成功
     */
    fun forceStopApp(packageName: String): Boolean {
        return try {
            // 使用shell命令强制停止应用（需要root权限或系统应用权限）
            val process = Runtime.getRuntime().exec(arrayOf("su", "-c", "am force-stop $packageName"))
            val exitValue = process.waitFor()
            exitValue == 0
        } catch (e: Exception) {
            Log.e(TAG, "Error stopping app: $packageName", e)
            false
        }
    }
    
    /**
     * 启动应用商店中的应用页面
     * 
     * @param packageName 应用包名
     * @return 操作是否成功
     */
    suspend fun openAppInStore(packageName: String): Boolean = withContext(Dispatchers.Main) {
        try {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName"))
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            
            context.startActivity(intent)
            return@withContext true
        } catch (e: Exception) {
            // 如果没有应用商店，尝试打开网页版
            try {
                val webIntent = Intent(Intent.ACTION_VIEW, 
                    Uri.parse("https://play.google.com/store/apps/details?id=$packageName"))
                webIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context.startActivity(webIntent)
                return@withContext true
            } catch (e2: Exception) {
                Log.e(TAG, "Error opening app in store: $packageName", e2)
                return@withContext false
            }
        }
    }
    
    /**
     * 打开应用设置页面
     * 
     * @param packageName 应用包名
     * @return 操作是否成功
     */
    suspend fun openAppSettings(packageName: String): Boolean = withContext(Dispatchers.Main) {
        try {
            val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = Uri.parse("package:$packageName")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            
            context.startActivity(intent)
            return@withContext true
        } catch (e: Exception) {
            Log.e(TAG, "Error opening app settings: $packageName", e)
            return@withContext false
        }
    }
    
    /**
     * 获取已安装的匹配应用列表
     * 
     * @param keyword 关键词，用于模糊匹配应用名称
     * @return 匹配的应用信息列表
     */
    fun findInstalledApps(keyword: String): List<AppInfo> {
        val result = mutableListOf<AppInfo>()
        
        try {
            val packageManager = context.packageManager
            val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                PackageManager.PackageInfoFlags.of(0)
            } else {
                0L
            }
            
            // 获取所有已安装的应用
            val installedPackages = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                packageManager.getInstalledPackages(flags)
            } else {
                @Suppress("DEPRECATION")
                packageManager.getInstalledPackages(0)
            }
            
            // 过滤并收集匹配的应用
            for (packageInfo in installedPackages) {
                val appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString()
                
                if (keyword.isEmpty() || appName.contains(keyword, ignoreCase = true)) {
                    result.add(
                        AppInfo(
                            packageName = packageInfo.packageName,
                            appName = appName,
                            versionName = packageInfo.versionName,
                            isSystemApp = (packageInfo.applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0
                        )
                    )
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error finding installed apps", e)
        }
        
        return result
    }
    
    /**
     * 应用信息数据类
     */
    data class AppInfo(
        val packageName: String,
        val appName: String,
        val versionName: String,
        val isSystemApp: Boolean
    )
} 